//
//  ChannelViewController.m
//  HuateVideo
//
//  Created by Tiger on 12-5-17.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ChannelViewController.h"
#import "SBJSON.h"
#import "ListViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "MySpaceViewController.h"
#import "PicturesViewController.h"
#import "CommonWebServices.h"
#import "TJSP.h"
#import "DataList.h"
#import "DetailViewController.h"
#import "SearchViewController.h"
@interface ChannelViewController ()

@end

@implementation ChannelViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    
    self.view.backgroundColor = TOOLBAR_TINTCOLOR;
    currentPage = 0;
    count = 5;
    array0 = [[NSMutableArray alloc]initWithArray:[UserDefaults objectForKey:@"TJLB"]];
    
    UIButton *searchBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    searchBtn.frame=CGRectMake(0, 0, 42, 31);
    [searchBtn setImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(pushSearchView) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* searchBarItem=[[UIBarButtonItem alloc] initWithCustomView:searchBtn];    
    self.navigationItem.rightBarButtonItem=searchBarItem;
    [searchBarItem release];
    
    NSString *path = [[NSBundle mainBundle]pathForResource: @"Channels" ofType: @"json"];
    NSString *channelListStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    SBJSON *json = [[SBJSON new] autorelease];
    channelArray = [[NSMutableArray alloc]initWithArray:[json objectWithString:channelListStr error:nil]];
    
    for (int i=0; i<[channelArray count]; i++) {
        if (i < [channelArray count]) {
            UIButton* item = [UIButton buttonWithType:UIButtonTypeCustom];
            [item addTarget:self action:@selector(toListViewController:) forControlEvents:UIControlEventTouchUpInside];
            item.tag = 1000+i;
            item.frame=CGRectMake(80*(i%4)+10, 180+80*floor((double)i/4.0), 60, 60);
            [self.view addSubview:item];
            
            item.layer.masksToBounds = YES; 
            item.layer.cornerRadius = 6.0; 
            item.layer.borderWidth = 1.0; 
            item.layer.borderColor = [LIGHT_COLOR CGColor]; 
            
            UIImageView *image = [[UIImageView alloc]initWithFrame:CGRectMake(14, 7, 32, 32)];
            image.image = [UIImage imageNamed:[[channelArray objectAtIndex:i] objectForKey:@"imgUrl"]];
            [item addSubview:image];
            [image release];
            
            UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 40, 60, 20)];
            title.text = LS([[channelArray objectAtIndex:i] objectForKey:@"appName"]);
            title.backgroundColor = [UIColor clearColor];
            title.textAlignment = UITextAlignmentCenter;
            title.textColor = LIGHT_COLOR;
            title.font = [UIFont systemFontOfSize:13.0];
            [item addSubview:title];
            [title release];
        }
    }
    
    count = [array0 count];
    if (count>0) {
        [self initTopView];
    }
    else {
        [self.view showProgressText:YES];
        [self loadData];
    }
}

-(void)pushSearchView{
    SearchViewController *searchViewController = [[SearchViewController alloc]init];
    [self.navigationController pushViewController:searchViewController animated:YES];
    [searchViewController release];
}

- (void)loadData
{
    CommonWebServices *webServ = [[CommonWebServices alloc] init];
    webServ.delegate = self;
    NSMutableDictionary *parma = [NSMutableDictionary dictionary];
    [parma setValue:@"0" forKey:@"Nodeid"];
    [webServ startRequestWithMode:@"Default" Action:@"GetTJW" Parma:parma Class:@"DataList" RootXML:@"GetTJWResult" resultIsArray:YES];
    [webServ release];
}

#pragma mark - CommonWebServicesDelegate

- (void)onCommonWebServicesWithCustomClass:(id)object {
    NSArray *list = [[NSArray alloc]initWithArray:((DataList *)object).List];
    
    if ([list count]>0) {
        for (int i=0; i<[list count]; i++) {
            TJSP *delePlay = [list objectAtIndex:i];
            
            if ([delePlay.Type intValue] == MovieChannelTypeHot) {
                [array0 addObject:delePlay];
            }
        }
        
        count = [array0 count];
        if (count>0) {
            [self initTopView];
        }
    }
    
    [self.view showProgressText:NO];
}

- (void)onCommonWebServicesFaild
{
    UIAlertView	*alertview = [[UIAlertView alloc] initWithTitle:LS(@"加载失败")  
                                                        message:LS(@"请检查网络连接和设置")
                                                       delegate:self 	
                                              cancelButtonTitle:LS(@"确定")
                                              otherButtonTitles:nil];		
    [alertview show];		
    [alertview release];
    
    
    [self.view showProgressText:NO];
}

- (void)dealloc
{
    [channelArray release];
    [scroll release];
    [pageControl release];
    [topTitle release];
    [array0 release];
    [super dealloc];
}

- (void)turnScrollPage
{
    currentPage++;
    if (currentPage == count) {
        currentPage = 0;
    }
    [UIView beginAnimations: nil context:nil];
    [UIView setAnimationDuration: 0.5];
    [scroll setContentOffset:CGPointMake(currentPage*320, 0) animated:YES];
    [UIView commitAnimations];
}

- (void)initTopView
{
    UIView *tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 320, 160)];
    tableHeaderView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:tableHeaderView];
    [tableHeaderView release];
    
    scroll = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, 320, 160)];
    scroll.backgroundColor = [UIColor clearColor];
    scroll.contentSize = CGSizeMake(320*count, 160);
    scroll.showsVerticalScrollIndicator = NO;
    scroll.showsHorizontalScrollIndicator = NO;
    scroll.tag = 10001;
    scroll.pagingEnabled = YES;
    scroll.delegate = self;
    [tableHeaderView addSubview:scroll];
    
    UIView *pageView = [[UIView alloc]initWithFrame:CGRectMake(0, 120, 320, 40)];
    pageView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
    [tableHeaderView addSubview:pageView];
    [pageView release];
    
    TJSP *delePlay1 = [array0 objectAtIndex:0];
    
    topTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 3, 320, 20)];
    topTitle.backgroundColor = [UIColor clearColor];
    topTitle.text = delePlay1.News_title;
    topTitle.textColor = [UIColor whiteColor];
    topTitle.font = [UIFont systemFontOfSize:15.0];
    topTitle.textAlignment = UITextAlignmentCenter;
    [pageView addSubview:topTitle];
    
    pageControl = [[UIPageControl alloc]initWithFrame:CGRectMake(0, 20, 320, 20)];
    pageControl.userInteractionEnabled = NO;
    pageControl.numberOfPages = count;
    pageControl.selected = 0;
    pageControl.backgroundColor = [UIColor clearColor];
    [pageView addSubview:pageControl];
    
    for (int i=0; i<count; i++) {
        UIButton *topImage = [UIButton buttonWithType:UIButtonTypeCustom];
        topImage.frame = CGRectMake(320*i, 0, 320, 160);
        topImage.tag = 20000+i;
        [topImage addTarget:self action:@selector(toDetailViewController:) forControlEvents:UIControlEventTouchUpInside];
        [topImage setBackgroundImage:[UIImage imageNamed:@"topImage.png"] forState:UIControlStateNormal];
        [scroll addSubview:topImage];
        
        TJSP *delePlay = [array0 objectAtIndex:i];
        
        if (!delePlay.iconImg && !delePlay.isImageLoading) {
            
            delePlay.isImageLoading = YES;
            [array0 replaceObjectAtIndex:i withObject:delePlay];
            
            ImageDownloader* imageDown = [[ImageDownloader alloc] init];
            imageDown.imageURL = delePlay.News_pic;
            imageDown.delegate = self;
            imageDown.tag = 20000+i;
            [imageDown startDownload:YES];
            [imageDown release];
        }
        else if (delePlay.iconImg) {
            [topImage setBackgroundImage:delePlay.iconImg forState:UIControlStateNormal];
        }
    }
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"TJLB"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:5.0 
                                                      target:self 
                                                    selector:@selector(turnScrollPage) 
                                                    userInfo:nil 
                                                     repeats:YES];
    [timer retain];
}

- (void)appImageDidLoad:(UIImage *)image withTag:(int)tag{
	if (image) {
        if (tag>=20000) {
            UIButton *topImage = (UIButton *)[scroll viewWithTag:tag];
            TJSP *delePlay = [array0 objectAtIndex:tag-20000];
            delePlay.iconImg = image;
            delePlay.isImageLoading = NO;
            [array0 replaceObjectAtIndex:tag-20000 withObject:delePlay];
            [topImage setBackgroundImage:delePlay.iconImg forState:UIControlStateNormal];
        }
    }
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.tag == 10001) {
        CGPoint p = scrollView.contentOffset;
        currentPage = floor((p.x - 320 / 2) / 320) + 1;
        pageControl.currentPage = currentPage;
        
        TJSP *delePlay = [array0 objectAtIndex:currentPage];
        topTitle.text = delePlay.News_title;
    }
}



- (MovieChannelType)movieChannelType:(NSInteger)t{
    MovieChannelType ty;
    switch (t) {
        case 0:
            ty=MovieChannelTypeMovie;
            break;
        case 1:
            ty=MovieChannelTypeSeries;
            break;
        case 2:
            ty=MovieChannelTypeMicroViedo;
            break;
        case 3:
            ty=MovieChannelTypeMusic;
            break;
        case 4:
            ty=MovieChannelTypePic;
            break;
        case 5:
            ty=MovieChannelTypeNews;
            break;
        case 6:
            ty=MovieChannelTypeOriginal;
            break;
        default:
            break;
    }
    return ty;
}
- (void)toListViewController:(UIButton *)sender
{
   
    if (sender.tag-1000 != 4&&sender.tag-1000 != 7) {
        ListViewController *listViewController = [[ListViewController alloc]init];
        listViewController.title = LS([[channelArray objectAtIndex:sender.tag-1000] objectForKey:@"appName"]);
        MovieChannelType t=[self movieChannelType:sender.tag-1000];
        listViewController.detailType=t;
        [self.navigationController pushViewController:listViewController animated:YES];
        [listViewController release];
    }else if (sender.tag-1000==4) {
        PicturesViewController*picv=[[PicturesViewController alloc] init];
        picv.title=LS([[channelArray objectAtIndex:sender.tag-1000] objectForKey:@"appName"]);
        [self.navigationController pushViewController:picv animated:YES];
        [picv release];
    }else {
        MySpaceViewController*myspace=[MySpaceViewController sharedInstance];
        [self.navigationController pushViewController:myspace animated:YES];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)toDetailViewController:(UIButton *)sender
{
    id movie;
    
    if (sender.tag>=20000) {
        movie = [array0 objectAtIndex:sender.tag-20000];
    }
    
    DetailViewController *detailViewController = [[DetailViewController alloc]init];
    detailViewController.type = 1;
    detailViewController.movie = movie;
    [self.navigationController pushViewController:detailViewController animated:YES];
    [detailViewController release];
}

@end
